package com.small.base.redis.core;


import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * RedisService
 *
 * @author miajio
 */
public class RedisService implements RedisInterface {

    private RedisTemplate<String, Object> redisTemplate;

    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public boolean expire(String key, long time, TimeUnit timeUnit) {
        return redisTemplate.expire(key, time, timeUnit);
    }

    @Override
    public long getTime(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }

    @Override
    public long getTime(String key) {
        return redisTemplate.getExpire(key);
    }

    @Override
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public boolean removeExpire(String key) {
        return redisTemplate.boundValueOps(key).persist();
    }

    @Override
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public void set(String key, String value, long time, TimeUnit timeUnit) {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, timeUnit);
        } else {
            redisTemplate.opsForValue().set(key, value);
        }
    }

    @Override
    public void batchSet(Map<String, String> keyAndValueSet) {
        redisTemplate.opsForValue().multiSet(keyAndValueSet);
    }

    @Override
    public void batchSetIfAbsent(Map<String, String> keyAndValueSet) {
        redisTemplate.opsForValue().multiSetIfAbsent(keyAndValueSet);
    }

    @Override
    public Object get(String key) {
        if (null != key) {
            return redisTemplate.opsForValue().get(key);
        }
        return null;
    }

    public RedisTemplate<String, Object> getRedisTemplate(){
        return redisTemplate;
    }


}
